package weather_;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

/**
 * @Author 汤舒青
 * @Version 1.0
 */

/**
 * 假设有个Socket服务器，
 * 提供查询气温，风力，pm2.5,湿度等气象服务，请设计服务端和客户端实现，提供退出功能，并使用多线程防止服务端堵塞。
 * 客户端选择要查询的类型，是气温，还是其他，服务端返回相应的值，
 * 并加上当前的日期（用yyyy-MM-dd hh:mm:ss格式），服务端通过多线程的方式提高性能,客户端发送和接收统一采用字符串格式
 * 用多线程提高响应速度
 */
public class Server {
    public static void main(String[] args) throws IOException {
        ServerSocket socket = null;
        try {
            socket = new ServerSocket(9090);
            while (true) {
                new ThreadServer(socket.accept()).start();

            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

class ThreadServer extends Thread {


    private final Socket s;

    public ThreadServer(Socket s) {
        this.s = s;
    }

    @Override
    public void run() {
        InputStream in = null;
        OutputStream out = null;
        Random random = new Random();
        try {
            System.out.println("已成功建立连接");
            in = s.getInputStream();
            out = s.getOutputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            String s = br.readLine();
            Date d1 = new Date();
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            String s1 = format.format(d1);
            if (s.equals("气温")) {
                out.write((s1 + "气温" + (random.nextBoolean() ? "" : "-") + (random.nextInt(50)) + "摄氏度").getBytes());
            } else if (s.equals("风力")) {
                out.write((s1 + "风力" + (random.nextInt(15)) + "级").getBytes());
            } else if (s.equals("PM2.5")) {
                out.write((s1 + "PM2.5为" + random.nextInt(10)).getBytes());
            } else if (s.equals("湿度")) {
                out.write((s1 + "湿度为" + (random.nextInt(15)) + "%rh").getBytes());

            } else {
                out.write("输入错误".getBytes());

            }


        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }


    }
}